{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Gaze Estimation using TAO GazeNet\n",
    "\n",
    "Transfer learning is the process of transferring learned features from one application to another. It is a commonly used training technique where you use a model trained on one task and re-train to use it on a different task. \n",
    "\n",
    "Train Adapt Optimize (TAO) Toolkit is a simple and easy-to-use Python based AI toolkit for taking purpose-built AI models and customizing them with users' own data.\n",
    "\n",
    "<img align=\"center\" src=\"https://d29g4g2dyqv443.cloudfront.net/sites/default/files/akamai/TAO/tlt-tao-toolkit-bring-your-own-model-diagram.png\" width=\"1080\"> "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Learning Objectives\n",
    "In this notebook, you will learn how to leverage the simplicity and convenience of TAO to:\n",
    "\n",
    "* Take a pretrained model and train a GazeNet model on subset of MPIIFaceGaze dataset\n",
    "* Run Inference on the trained model\n",
    "* Export the retrained model to a .etlt file for deployment to DeepStream SDK\n",
    "\n",
    "At the end of this notebook, you will have generated a trained and optimized `gaze estimation` model, \n",
    "which you may deploy via [DeepStream](https://developer.nvidia.com/deepstream-sdk).\n",
    "\n",
    "### Table of Contents\n",
    "\n",
    "This notebook shows an example of gaze estimation using GazeNet in the Train Adapt Optimize (TAO) Toolkit.\n",
    "\n",
    "0. [Set up env variables, map drives, and install dependencies](#head-0)\n",
    "1. [Install the TAO launcher](#head-1)\n",
    "2. [Prepare dataset and pre-trained model](#head-2) <br>\n",
    "    2.1 [Verify downloaded dataset](#head-2-1) <br>\n",
    "    2.2 [Convert datasets and labels to required format](#head-2-2) <br>\n",
    "    2.3 [Verify dataset generation](#head-2-3) <br>\n",
    "    2.4 [Download pre-trained model](#head-2-4) <br>\n",
    "3. [Generate tfrecords from labels in json format](#head-3)\n",
    "4. [Provide training specification](#head-4)\n",
    "5. [Run TAO training](#head-5)\n",
    "6. [Evaluate trained models](#head-6)\n",
    "7. [Run inference for a set of images](#head-7)\n",
    "8. [Deploy](#head-8)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 0. Set up env variables, map drives and install dependencies <a class=\"anchor\" id=\"head-0\"></a>\n",
    "When using the purpose-built pretrained models from NGC, please make sure to set the `$KEY` environment variable to the key as mentioned in the model overview. Failing to do so, can lead to errors when trying to load them as pretrained models.\n",
    "\n",
    "The following notebook requires the user to set an env variable called the `$LOCAL_PROJECT_DIR` as the path to the users' workspace. Please note that the dataset to run this notebook is expected to reside in the `$LOCAL_PROJECT_DIR/gazenet/data`, while the TAO experiment generated collaterals will be output to `$LOCAL_PROJECT_DIR/gazenet`. More information on how to set up the dataset and the supported steps in the TAO workflow are provided in the subsequent cells.\n",
    "\n",
    "*Note: This notebook currently is by default set up to run training using 1 GPU. To use more GPU's please update the env variable `$NUM_GPUS` accordingly*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Setting up env variables for cleaner command line commands.\n",
    "import os\n",
    "\n",
    "%env KEY=nvidia_tlt\n",
    "%env NUM_GPUS=1\n",
    "%env USER_EXPERIMENT_DIR=/workspace/tao-experiments/gazenet\n",
    "%env DATA_DOWNLOAD_DIR=/workspace/tao-experiments/gazenet/data\n",
    "\n",
    "# Set this path if you don't run the notebook from the samples directory.\n",
    "# %env NOTEBOOK_ROOT=~/tao-samples/gazenet\n",
    "\n",
    "# Please define this local project directory that needs to be mapped to the TAO docker session.\n",
    "# The dataset is expected to be present in $LOCAL_PROJECT_DIR/gazenet/data, while the results for the steps\n",
    "# in this notebook will be stored at $LOCAL_PROJECT_DIR/gazenet\n",
    "# !PLEASE MAKE SURE TO UPDATE THIS PATH!.\n",
    "%env LOCAL_PROJECT_DIR=FIXME\n",
    "\n",
    "# $SAMPLES_DIR is the path to the sample notebook folder and the dependency folder\n",
    "# $SAMPLES_DIR/deps should exist for dependency installation\n",
    "%env SAMPLES_DIR=FIXME\n",
    "\n",
    "os.environ[\"LOCAL_DATA_DIR\"] = os.path.join(\n",
    "    os.getenv(\"LOCAL_PROJECT_DIR\", os.getcwd()),\n",
    "    \"gazenet/data\"\n",
    ")\n",
    "os.environ[\"LOCAL_EXPERIMENT_DIR\"] = os.path.join(\n",
    "    os.getenv(\"LOCAL_PROJECT_DIR\", os.getcwd()),\n",
    "    \"gazenet\"\n",
    ")\n",
    "\n",
    "# The sample spec files are present in the same path as the downloaded samples.\n",
    "os.environ[\"LOCAL_SPECS_DIR\"] = os.path.join(\n",
    "    os.getenv(\"NOTEBOOK_ROOT\", os.getcwd()),\n",
    "    \"specs\"\n",
    ")\n",
    "%env SPECS_DIR=/workspace/tao-experiments/gazenet/specs\n",
    "\n",
    "# Showing list of specification files.\n",
    "!ls -rlt $LOCAL_SPECS_DIR"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The cell below maps the project directory on your local host to a workspace directory in the TAO docker instance, so that the data and the results are mapped from in and out of the docker. For more information please refer to the [launcher instance](https://docs.nvidia.com/tao/tao-toolkit/text/tao_launcher.html) in the user guide.\n",
    "\n",
    "When running this cell on AWS, update the drive_map entry with the dictionary defined below, so that you don't have permission issues when writing data into folders created by the TAO docker.\n",
    "\n",
    "```json\n",
    "drive_map = {\n",
    "    \"Mounts\": [\n",
    "            # Mapping the data directory\n",
    "            {\n",
    "                \"source\": os.environ[\"LOCAL_PROJECT_DIR\"],\n",
    "                \"destination\": \"/workspace/tao-experiments\"\n",
    "            },\n",
    "            # Mapping the specs directory.\n",
    "            {\n",
    "                \"source\": os.environ[\"LOCAL_SPECS_DIR\"],\n",
    "                \"destination\": os.environ[\"SPECS_DIR\"]\n",
    "            },\n",
    "        ],\n",
    "    \"DockerOptions\": {\n",
    "        \"user\": \"{}:{}\".format(os.getuid(), os.getgid())\n",
    "    }\n",
    "}\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Mapping up the local directories to the TAO docker.\n",
    "import json\n",
    "mounts_file = os.path.expanduser(\"~/.tao_mounts.json\")\n",
    "\n",
    "# Define the dictionary with the mapped drives\n",
    "drive_map = {\n",
    "    \"Mounts\": [\n",
    "        # Mapping the data directory\n",
    "        {\n",
    "            \"source\": os.environ[\"LOCAL_PROJECT_DIR\"],\n",
    "            \"destination\": \"/workspace/tao-experiments\"\n",
    "        },\n",
    "        # Mapping the specs directory.\n",
    "        {\n",
    "            \"source\": os.environ[\"LOCAL_SPECS_DIR\"],\n",
    "            \"destination\": os.environ[\"SPECS_DIR\"]\n",
    "        },\n",
    "    ]\n",
    "}\n",
    "\n",
    "# Writing the mounts file.\n",
    "with open(mounts_file, \"w\") as mfile:\n",
    "    json.dump(drive_map, mfile, indent=4)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!cat ~/.tao_mounts.json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Install requirement\n",
    "!pip3 install Cython==0.29.36\n",
    "!pip3 install -r $SAMPLES_DIR/deps/requirements-pip.txt"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Install the TAO launcher <a class=\"anchor\" id=\"head-1\"></a>\n",
    "The TAO launcher is a python package distributed as a python wheel listed in PyPI. You may install the launcher by executing the following cell.\n",
    "\n",
    "Please note that TAO Toolkit recommends users run the TAO launcher in a virtual env with python 3.6.9. You may follow the instruction on this [page](https://virtualenvwrapper.readthedocs.io/en/latest/install.html) to set up a python virtual env using the `virtualenv` and `virtualenvwrapper` packages. Once you have set up virtualenvwrapper, please set the version of python to be used in the virtual env by using the `VIRTUALENVWRAPPER_PYTHON` variable. You may do so by running\n",
    "\n",
    "```sh\n",
    "export VIRTUALENVWRAPPER_PYTHON=/path/to/bin/python3.x\n",
    "```\n",
    "where x >= 6 and <= 8\n",
    "\n",
    "We recommend performing this step first and then launching the notebook from the virtual environment. In addition to installing TAO python package, please make sure of the following software requirements:\n",
    "* python >=3.7, <=3.10.x\n",
    "* docker-ce > 19.03.5\n",
    "* docker-API 1.40\n",
    "* nvidia-container-toolkit > 1.3.0-1\n",
    "* nvidia-container-runtime > 3.4.0-1\n",
    "* nvidia-docker2 > 2.5.0-1\n",
    "* nvidia-driver > 455+\n",
    "\n",
    "Once you have installed the pre-requisites, please log in to the docker registry nvcr.io by following the command below\n",
    "\n",
    "```sh\n",
    "docker login nvcr.io\n",
    "```\n",
    "\n",
    "You will be triggered to enter a username and password. The username is `$oauthtoken` and the password is the API key generated from `ngc.nvidia.com`. Please follow the instructions in the [NGC setup guide](https://docs.nvidia.com/ngc/ngc-overview/index.html#generating-api-key) to generate your own API key."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Skip this cell if the TAO launcher was already installed.\n",
    "!pip3 install nvidia-tao"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# View the version of the TAO launcher\n",
    "!tao info"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Prepare dataset and pre-trained model <a class=\"anchor\" id=\"head-2\"></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "This notebook uses a subset of MPIIFaceGaze dataset to illustrate the input data format for GazeNet and the procedures to use the generated data.\n",
    "\n",
    "Please download the MPIIFaceGaze dataset from the following website:\n",
    "https://www.mpi-inf.mpg.de/departments/computer-vision-and-machine-learning/research/gaze-based-human-computer-interaction/its-written-all-over-your-face-full-face-appearance-based-gaze-estimation\n",
    "\n",
    "The labels for this subset based on required json format can be obtained from:\n",
    "`$SAMPLES_DIR/gazenet/sample_labels`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# check if the label file is presented\n",
    "!if [ ! -f $SAMPLES_DIR/gazenet/sample_labels/data_factory.zip ]; then echo 'Label file not found, please check your sample path.'; else echo 'Found label file.';fi"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After downloading the data, please unzip it to the `MPIIFaceGaze` folder and place the folder in `$DATA_DOWNLOAD_DIR`\n",
    "\n",
    "After downloading the labels, please unzip it to the `data_factory` folder and place the folder in `MPIIFaceGaze`\n",
    "\n",
    "You will then have the following path\n",
    "* input data in `$LOCAL_DATA_DIR/MPIIFaceGaze`\n",
    "* labels in `$LOCAL_DATA_DIR/MPIIFaceGaze/data_factory`"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### A. Verify downloaded dataset <a class=\"anchor\" id=\"head-2-1\"></a>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Check the dataset is present\n",
    "!mkdir -p $LOCAL_DATA_DIR\n",
    "!if [ ! -d $LOCAL_DATA_DIR/MPIIFaceGaze ]; then echo 'Data folder not found, please download.'; else echo 'Found Data folder.';fi\n",
    "!if [ ! -d $LOCAL_DATA_DIR/MPIIFaceGaze/data_factory ]; then echo 'Label folder not found, please download.'; else echo 'Found Labels folder.';fi"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Sample json label.\n",
    "!sed -n 1,201p $LOCAL_DATA_DIR/MPIIFaceGaze/data_factory/day03/p01/p01_day03.json"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### B. Convert datasets and labels to required format <a class=\"anchor\" id=\"head-2-2\"></a>\n",
    "\n",
    "A script is provided to convert the subset of `MPIIFaceGaze` dataset and downloaded labels to a required folder structure and dataset format."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!python3 mpiifacegaze_convert.py --data_path $LOCAL_DATA_DIR/MPIIFaceGaze \\\n",
    "                                 --json_label_root_path $LOCAL_DATA_DIR/MPIIFaceGaze"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### C. Verify dataset generation <a class=\"anchor\" id=\"head-2-3\"></a>\n",
    "\n",
    "A dataset folder with above-mentioned subset is created. All the required data to run GazeNet is saved under this folder.\n",
    "* Generated data folder in `$LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset/p01-day03`\n",
    "* Generated inference data folder in `$LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset/inference-set`\n",
    "\n",
    "The converted dataset should have the following structure.\n",
    "\n",
    "* `Config` folder in `$LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset/p01-day03/Config`\n",
    "* `Data` folder in `$LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset/p01-day03/Data`\n",
    "* `Labels` folder in `$LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset/p01-day03/json_datafactory_v2`\n",
    "\n",
    "The inference dataset should have the following structure.\n",
    "\n",
    "* `Config` folder in `$LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset/inference-set/Config`\n",
    "* `Data` folder in `$LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset/inference-set/Data`\n",
    "* `Labels` folder in `$LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset/inference-set/json_datafactory_v2`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Check the generated data is present\n",
    "!if [ ! -d $LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset/p01-day03 ]; then echo 'Generated data folder not found, please regenerated.'; else echo 'Found generated data folder.';fi\n",
    "!if [ ! -d $LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset/p01-day03/Config ]; then echo 'Config folder not found, please regenerated.'; else echo 'Found Config folder.';fi\n",
    "!if [ ! -d $LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset/p01-day03/Data ]; then echo 'Data folder not found, please regenerated.'; else echo 'Found Data folder.';fi\n",
    "!if [ ! -d $LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset/p01-day03/json_datafactory_v2 ]; then echo 'Labels folder not found, please regenerated.'; else echo 'Found Labels folder.';fi\n",
    "\n",
    "# Check the inference data is present\n",
    "!if [ ! -d $LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset/inference-set ]; then echo 'Inference data folder not found, please regenerated.'; else echo 'Found inference data folder.';fi\n",
    "!if [ ! -d $LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset/inference-set/Config ]; then echo 'Config folder not found, please regenerated.'; else echo 'Found Config folder.';fi\n",
    "!if [ ! -d $LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset/inference-set/Data ]; then echo 'Data folder not found, please regenerated.'; else echo 'Found Data folder.';fi\n",
    "!if [ ! -d $LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset/inference-set/json_datafactory_v2 ]; then echo 'Labels folder not found, please regenerated.'; else echo 'Found Labels folder.';fi"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### D. Download pre-trained model <a class=\"anchor\" id=\"head-2-4\"></a>\n",
    "\n",
    "Please follow the instructions in the following to download and verify the pretrained model for gazenet.\n",
    "\n",
    "For GazeNet pretrained model please download model: `nvidia/tao/gazenet:trainable_v1.0`.\n",
    "\n",
    "After downloading the pre-trained model, please place the files in `$LOCAL_EXPERIMENT_DIR/pretrain_models`\n",
    "You will then have the following path\n",
    "\n",
    "* pretrained model in `$LOCAL_EXPERIMENT_DIR/pretrain_models/gazenet_vtrainable_v1.0/model.tlt`"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Installing NGC CLI on the local machine.\n",
    "## Download and install\n",
    "%env CLI=ngccli_cat_linux.zip\n",
    "!mkdir -p $LOCAL_PROJECT_DIR/ngccli\n",
    "\n",
    "# Remove any previously existing CLI installations\n",
    "!rm -rf $LOCAL_PROJECT_DIR/ngccli/*\n",
    "!wget \"https://ngc.nvidia.com/downloads/$CLI\" -P $LOCAL_PROJECT_DIR/ngccli\n",
    "!unzip -u \"$LOCAL_PROJECT_DIR/ngccli/$CLI\" -d $LOCAL_PROJECT_DIR/ngccli/\n",
    "!rm $LOCAL_PROJECT_DIR/ngccli/*.zip \n",
    "os.environ[\"PATH\"]=\"{}/ngccli/ngc-cli:{}\".format(os.getenv(\"LOCAL_PROJECT_DIR\", \"\"), os.getenv(\"PATH\", \"\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# List models available in the model registry.\n",
    "!ngc registry model list nvidia/tao/gazenet:*"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create the target destination to download the model.\n",
    "!mkdir -p $LOCAL_EXPERIMENT_DIR/pretrain_models/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Download the pretrained model from NGC\n",
    "!ngc registry model download-version nvidia/tao/gazenet:trainable_v1.0 \\\n",
    "    --dest $LOCAL_EXPERIMENT_DIR/pretrain_models/"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!ls -rlt $LOCAL_EXPERIMENT_DIR/pretrain_models/gazenet_vtrainable_v1.0"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Check the dataset is present\n",
    "!if [ ! -f $LOCAL_EXPERIMENT_DIR/pretrain_models/gazenet_vtrainable_v1.0/model.tlt ]; then echo 'Pretrain model file not found, please download.'; else echo 'Found Pretrain model file.';fi"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Generate tfrecords from labels in json format <a class=\"anchor\" id=\"head-3\"></a>\n",
    "* Create the tfrecords using the dataset_convert command "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!tao model gazenet dataset_convert -folder-suffix pipeline \\\n",
    "                             -norm_folder_name Norm_Data \\\n",
    "                             -sets p01-day03 \\\n",
    "                             -data_root_path $DATA_DOWNLOAD_DIR/MPIIFaceGaze/sample-dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!ls -rl $LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# check the tfrecords are presented\n",
    "!if [ ! -d $LOCAL_DATA_DIR/MPIIFaceGaze/sample-dataset/p01-day03/Ground_Truth_DataFactory_pipeline ]; then echo 'Tfrecords folder not found, please generate.'; else echo 'Found Tfrecords folder.';fi"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Provide training specification <a class=\"anchor\" id=\"head-4\"></a>\n",
    "* Tfrecords for the train datasets\n",
    "    * In order to use the newly generated tfrecords for training, update the 'ground_truth_folder_name' and 'tfrecords_directory_path' parameters of 'dataset_info' section in the spec file at `$SPECS_DIR/gazenet_tlt_pretrain.yaml`\n",
    "* Pre-trained model path\n",
    "    * Update \"pretrained_model_path\" in the spec file at `$SPECS_DIR/gazenet_tlt_pretrain.yaml`\n",
    "    * If you want to training from random weights with your own data, you can enter \"null\" for \"pretrained_model_path\" section\n",
    "* Augmentation parameters for on the fly data augmentation\n",
    "* Other training (hyper-)parameters such as batch size, number of epochs, learning rate etc."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!cat $LOCAL_SPECS_DIR/gazenet_tlt_pretrain.yaml"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Run TAO training <a class=\"anchor\" id=\"head-5\"></a>\n",
    "* Provide the sample spec file and the output directory location for models\n",
    "\n",
    "*Note: The training may take hours to complete. Also, the remaining notebook, assumes that the training was done in single-GPU mode. \n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!tao model gazenet train -e $SPECS_DIR/gazenet_tlt_pretrain.yaml \\\n",
    "                   -r $USER_EXPERIMENT_DIR/experiment_result/exp1 \\\n",
    "                   -k $KEY"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!ls -lh $LOCAL_EXPERIMENT_DIR/experiment_result/exp1"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Evaluate the trained model <a class=\"anchor\" id=\"head-6\"></a>\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!tao model gazenet evaluate -type kpi_testing \\\n",
    "                      -m $USER_EXPERIMENT_DIR/experiment_result/exp1 \\\n",
    "                      -e $SPECS_DIR/gazenet_tlt_pretrain.yaml \\\n",
    "                      -k $KEY"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!ls -lh $LOCAL_EXPERIMENT_DIR/experiment_result/exp1/KPI_TMP"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Visualize Inference <a class=\"anchor\" id=\"head-7\"></a>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!tao model gazenet inference -e $SPECS_DIR/gazenet_tlt_pretrain.yaml \\\n",
    "                       -i $DATA_DOWNLOAD_DIR/MPIIFaceGaze/sample-dataset/inference-set \\\n",
    "                       -m $USER_EXPERIMENT_DIR/experiment_result/exp1/model.tlt \\\n",
    "                       -o $USER_EXPERIMENT_DIR/experiment_result/exp1 \\\n",
    "                       -k $KEY"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!ls -lh $LOCAL_EXPERIMENT_DIR/experiment_result/exp1/result.txt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "import cv2\n",
    "import numpy as np\n",
    "import os\n",
    "import json\n",
    "import IPython.display\n",
    "import PIL.Image\n",
    "from utils_gazeviz import load_cam_intrinsics,\\\n",
    "        get_landmarks_dict, visualize_frame\n",
    "\n",
    "# load data\n",
    "data_root_path = os.path.join(os.environ['LOCAL_DATA_DIR'],\n",
    "                              'MPIIFaceGaze/sample-dataset/inference-set')\n",
    "print(data_root_path)\n",
    "# load calibration\n",
    "config_path = os.path.join(data_root_path, 'Config')\n",
    "calib = {}\n",
    "camera_mat, distortion_coeffs = load_cam_intrinsics(config_path)\n",
    "distortion_coeffs = distortion_coeffs[0:5]\n",
    "calib['cam'] = camera_mat\n",
    "calib['dist'] = distortion_coeffs\n",
    "\n",
    "# load json files\n",
    "json_file_folder = os.path.join(data_root_path, 'json_datafactory_v2')\n",
    "landmarks_dict = get_landmarks_dict(json_file_folder)\n",
    "assert len(landmarks_dict.keys()) > 0\n",
    "\n",
    "# visualize each frame in the result file\n",
    "num_viz_frames = 5\n",
    "result_path = os.path.join(os.environ['LOCAL_EXPERIMENT_DIR'],\n",
    "                           \"experiment_result/exp1/result.txt\")\n",
    "\n",
    "with open(result_path, 'r') as reader:\n",
    "    lines = reader.readlines()\n",
    "\n",
    "num_lines = len(lines)\n",
    "num_viz_frames = min(num_viz_frames, num_lines)\n",
    "for k in range(0, num_viz_frames):\n",
    "    content = lines[k]\n",
    "    line_info = content.split(' ')\n",
    "    old_frame_path = line_info[0]\n",
    "    sub_path = old_frame_path.split(os.environ['DATA_DOWNLOAD_DIR'])[-1]\n",
    "    frame_path = os.environ['LOCAL_DATA_DIR'] + sub_path\n",
    "    cam_coord = np.array(line_info[1:4], dtype=np.float32)\n",
    "    frame_name = frame_path.split('/')[-1]\n",
    "    landmarks_2D = landmarks_dict[frame_name]\n",
    "    display_frame, le_px, le_por, re_px, re_por = visualize_frame(frame_path, landmarks_2D, cam_coord, calib)\n",
    "    # Visualize selected landmarks\n",
    "    cv2.arrowedLine(display_frame, tuple(le_px), tuple(le_por), (0, 255, 0), thickness=2, tipLength=0.05)\n",
    "    cv2.arrowedLine(display_frame, tuple(re_px), tuple(re_por), (0, 255, 0), thickness=2, tipLength=0.05)\n",
    "    IPython.display.display(PIL.Image.fromarray(display_frame))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 8. Deploy <a class=\"anchor\" id=\"head-8\"></a>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!mkdir -p $LOCAL_EXPERIMENT_DIR/experiment_dir_final\n",
    "# Removing a pre-existing copy of the etlt if there has been any.\n",
    "import os\n",
    "output_file=os.path.join(os.environ['LOCAL_EXPERIMENT_DIR'],\n",
    "                         \"experiment_dir_final/gazenet_onnx.etlt\")\n",
    "if os.path.exists(output_file):\n",
    "    os.system(\"rm {}\".format(output_file))\n",
    "\n",
    "!tao model gazenet export -m $USER_EXPERIMENT_DIR/experiment_result/exp1/model.tlt \\\n",
    "                    -o $USER_EXPERIMENT_DIR/experiment_dir_final/gazenet_onnx.etlt \\\n",
    "                    -t tfonnx \\\n",
    "                    -k $KEY"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# check the Deployed file is presented\n",
    "!if [ ! -f $LOCAL_EXPERIMENT_DIR/experiment_dir_final/gazenet_onnx.etlt ]; then echo 'Deployed file not found, please generate.'; else echo 'Found Deployed file folder.';fi"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
